#!/usr/bin/env python3.6
# -*- encoding: utf-8 -*-
'''
@File    :   __init__.py
@Time    :   2020/10/12 00:02:56
@Author  :   Tang Jing 
@Version :   1.0.0
@Contact :   yeihizhi@163.com
@License :   (C)Copyright 2020
@Desc    :   None
'''

# here put the import lib
from rest_framework import serializers
from rest_framework.request import Request
from rest_framework.test import APIRequestFactory
from core.log import logging
from rest_framework.response import Response as bResponse
from core.config import REST_FRAMEWORK_DOMAIN
# code start


factory = APIRequestFactory()
request = factory.get('/')
request._current_scheme_host = REST_FRAMEWORK_DOMAIN  # setting the server domain

serializer_context = {
    'request': Request(request),
}


def Response(stateCode, data, error= None):
    if stateCode!=200:
        if error:
            logging.error(error)
    return bResponse({"state": stateCode, "msg": data})

class dynamicSerializer(serializers.ModelSerializer):
    class Meta:
        model= None
        fields="__all__"
    def __init__(self, instance=None, data=...,m_model=None,fields=None, **kwargs):
        if m_model:
            self.Meta.model= m_model
        if fields:
            self.Meta.fields= fields
        super().__init__(instance, data, **kwargs)
        
class serializer(serializers.ModelSerializer):
    def __init__(self, *args, **kwargs):
        fields= kwargs.pop('fields',None)
        super().__init__(*args,**kwargs)
        
        if fields is not None:
            allowed = set(fields)
            existing= set(self.fields.keys())
            for field_name in existing - allowed:
                self.fields.pop(field_name)